﻿<#
	1. netstat -ano | findstr $specialPort
	2. 找到状态为LISTENING
	3. taskkill /f /pid $pidNum
	
	权限设置 Set-ExecutionPolicy Unrestricted
	
	以管理员权限运行powershell, 执行命名:  set-executionpolicy remotesigned
#>

function killAllProcess ($specialPort)
{
        <#
    # 干掉所有占据指定端口的进程
    # $pid 该变量被内置, 表示当前powershell进程
    #>
    $processStr = netstat -ano | findstr $specialPort;
    if ($processStr.Length -eq 0)
    {
        return;
    }
    $processes = $processStr.Split([Environment]::NewLine);

    foreach ($process in $processes)
    {
        $components = $process.Split(" ",[StringSplitOptions]::RemoveEmptyEntries);
        <# [
            TCP, 
            0.0.0.0:8080, 
            0.0.0.0:0, 
            LISTENING, 
            8644
        ]#>
        $pidNum = $components[4]; 
         $pidNum
		 ps -Id $pidNum
        taskkill /f /pid $pidNum
    }
}

$port = $args[0];

if ($port)
{
    #Do Nothing
}
else{
     $port = '8080';
}

killAllProcess $port